﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace Monocle.Controllers.StaticHelpers
{
    public static class WebStream
    {
        /// <summary>
        /// Gets stream of data from a given website URL
        /// </summary>
        /// <param name="url">URL of the website</param>
        /// <returns>String</returns>
        public static String GetWebStream(String url)
        {
            try
            {
                // used to build entire input
                var sb = new StringBuilder();

                // used on each read operation
                byte[] buf = new byte[8192];

                // prepare the web page we will be asking for
                var request = (HttpWebRequest)
                    WebRequest.Create(url);

                // execute the request
                var response = (HttpWebResponse)
                    request.GetResponse();

                // we will read data via the response stream
                var resStream = response.GetResponseStream();

                string tempString = null;
                var count = 0;

                do
                {
                    // fill the buffer with data
                    count = resStream.Read(buf, 0, buf.Length);

                    // make sure we read some data
                    if (count != 0)
                    {
                        // translate from bytes to ASCII text
                        tempString = Encoding.ASCII.GetString(buf, 0, count);

                        // continue building the string
                        sb.Append(tempString);
                    }
                }
                while (count > 0); // any more data to read?

                return sb.ToString();
            }
            catch (Exception e)
            {
                return "";
            }
        }


        public static String GetFacebookImage(String url)
        {
            // used to build entire input
            var sb = new StringBuilder();

            // used on each read operation
            byte[] buf = new byte[8192];

            // prepare the web page we will be asking for
            var request = (HttpWebRequest)
                WebRequest.Create(url);

            // execute the request
            var response = (HttpWebResponse)
                request.GetResponse();

            return response.ResponseUri.ToString();
        }
    }
}